package com.kayo.specimen.controller;

import com.kayo.specimen.annotion.CurrentUser;
import com.kayo.specimen.model.Menu;
import com.kayo.specimen.model.User;
import com.kayo.specimen.service.MenuService;
import com.kayo.specimen.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequiresPermissions("主页")
@Controller
@RequestMapping({"/home",""})
public class HomeController {

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserService userService;

    @RequestMapping({"","/index"})
    public ModelAndView home(@CurrentUser User user){
        ModelAndView modelAndView = new ModelAndView("/views/index");
        List<Menu> grantedMenus = userService.getGrantedMenus(user.getId());

        List<String> categories = grantedMenus.stream().sorted(Comparator.comparingInt(Menu::getIndex)).map(f -> f.getCategory()).distinct().collect(Collectors.toList());

        Map<String,Menu[]> map=new HashMap<>();
        for(String category:categories){
            map.put(category,grantedMenus.stream().sorted(Comparator.comparingInt(Menu::getIndex)).filter(f->f.getCategory().equals(category)).collect(Collectors.toList()).toArray(new Menu[0]));
        }
        modelAndView.addObject("user", user);
        modelAndView.addObject("categories",categories);
        modelAndView.addObject("menus",map);
        return modelAndView;
    }

    @RequestMapping("/console")
    public String console(){
        return "/views/home/console";
    }
}
